package com.huahang.fashionpress.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huahang.fashionpress.config.ParamConfig;
import com.huahang.fashionpress.dataobject.PageOrderMasterList;
import com.huahang.fashionpress.enums.ExceptionEnum;
import com.huahang.fashionpress.enums.OrderEnum;
import com.huahang.fashionpress.enums.OrderIsdelEnum;
import com.huahang.fashionpress.exception.ResultException;
import com.huahang.fashionpress.form.FormOrder;
import com.huahang.fashionpress.form.FormProduct;
import com.huahang.fashionpress.mapper.*;
import com.huahang.fashionpress.model.*;
import com.huahang.fashionpress.service.OrderService;
import com.huahang.fashionpress.util.IdUtils;
import com.huahang.fashionpress.vo.OrderDetailVO;
import com.huahang.fashionpress.vo.OrderMasterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 阿俊哥
 * @Date: 2019/8/26 19:19
 * @Version 1.0
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    ImgMapper imgMapper;

    @Resource
    ProductMapper productMapper;

    @Resource
    OrderProductMapper orderProductMapper;

    @Resource
    AddressMapper addressMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    ParamConfig paramConfig;

    /**
     * 查询主订单
     * @return
     */
    @Override
    public PageOrderMasterList selectOrderList(int size, int pagenum) {

        //查询订单表查到所有的订单
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_isDel", OrderIsdelEnum.NOT_DELETE.getCode());
        Page<Order> page = new Page<>(pagenum,size);
        Page<Order> pages = (Page<Order>) orderMapper.selectPage(page,queryWrapper);
        //转换为list OrderMasterVO
        List<Order> orderList = pages.getRecords();
        List<OrderMasterVO> orderMasterVOList = new ArrayList<>();
        OrderMasterVO orderMasterVO = null;
        for (Order order : orderList) {
            Address address =  addressMapper.selectById(order.getAddressId());
            User user = userMapper.selectById(order.getUserId());
            orderMasterVO = OrderToOderMasterVO(order,address,user);
            List<OrderDetailVO> orderDetailVOList = this.selectOrderDetails(order.getOrderId());
            orderMasterVO.setOrderDetailVOList(orderDetailVOList);
            orderMasterVOList.add(orderMasterVO);
        }
        PageOrderMasterList pageOrderMasterList = new PageOrderMasterList(pages.getCurrent(), pages.getTotal()/10+1, orderMasterVOList);


        return pageOrderMasterList;
    }

    /**
     * 修改订单状态
     * @param orderId
     * @param orderStatus
     * @return
     */
    @Override
    @Transactional
    public boolean updateOrderStatus(String orderId,int orderStatus) {

        if(orderId==null||orderId.equals("")){
            log.info("【订单管理】修改订单参数错误 错误参数orderId"+orderId);
            throw new ResultException(ExceptionEnum.PARAM_ERROR);

        }
        if(0==orderStatus){
            log.info("【订单管理】修改订单参数错误 错误参数orderStatus"+orderStatus);
            throw new ResultException(ExceptionEnum.PARAM_ERROR);

        }
        Order order = orderMapper.selectById(orderId);
        order.setOrderStatus(orderStatus);
        int result = orderMapper.updateById(order);
        if(result>0){
            return true;
        }

        return false;
    }

    /**
     * 查询订单详情的列表
     * @param orderId
     * @return
     */
    @Override
    public List<OrderDetailVO> selectOrderDetails(String orderId) {
        //1.根据orderid 找到productIdList
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_id", orderId);
        List<OrderProduct> orderProductList  = orderProductMapper.selectList(queryWrapper);
        List<OrderDetailVO> orderDetailVOList = new ArrayList<>();
        //2.根据productlist  遍历找到img list
        for (OrderProduct orderProduct : orderProductList) {
            Product product = productMapper.selectById(orderProduct.getProductId());
            QueryWrapper<Img> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("product_id", product.getProductId());
            queryWrapper1.eq("img_status", 1);
            Img img = imgMapper.selectOne(queryWrapper1);
            //处理img是null的情况
            if(img==null){
                Img img1 = new Img();
                img1.setImgName(paramConfig.getImgUrl());
                img = img1;
            }
            //3.设置属性
            OrderDetailVO orderDetailVO = productToorderDetailVO(product,img,orderProduct);
            orderDetailVOList.add(orderDetailVO);
        }
        return orderDetailVOList;

    }

    @Override
    public OrderMasterVO selectOrderById(String orderId) {
        Order order = orderMapper.selectById(orderId);
        if(order==null){
            log.info("【订单管理】根据id查询订单出错，未找到该订单");
            return null;

        }
        User user = userMapper.selectById(order.getUserId());
        Address address = addressMapper.selectById(order.getAddressId());
        return OrderToOderMasterVO(order, address, user);
    }

    private OrderDetailVO productToorderDetailVO(Product product, Img img,OrderProduct orderProduct) {

        OrderDetailVO orderDetailVO = new OrderDetailVO(product.getProductName(),img.getImgName(), product.getProductPrice(), orderProduct.getProductQuantity(), new BigDecimal(orderProduct.getProductQuantity()).multiply(product.getProductPrice()));
        return orderDetailVO;
    }

    private OrderMasterVO OrderToOderMasterVO(Order order, Address address, User user) {

        OrderMasterVO orderMasterVO = new OrderMasterVO();
        orderMasterVO.setOrderId(order.getOrderId());
        orderMasterVO.setOrderPrice(order.getOrderPrice());
        orderMasterVO.setOrderStatus(order.getOrderStatus());
        orderMasterVO.setOrderDate(order.getOrderDate());
        orderMasterVO.setUserUsername(user.getUserUsername());
        orderMasterVO.setAddressBase(address.getAddressBase());
        orderMasterVO.setAddressName(address.getAddressName());
        orderMasterVO.setAddressPhone(address.getAddressPhone());
        orderMasterVO.setAddressPlace(address.getAddressPlace());
        return orderMasterVO;
    }

    /**
     * 添加一个订单方法
     * 先添加订单详情，之后查询订单id，再添加商品列表
     * @param formOrder 订单详情
     * @param productList 订单商品列表
     * @return
     */
    @Override
    public String addSingleOrder(FormOrder formOrder, List<FormProduct> productList) {
        Date date = new Date();
        String orderID = IdUtils.generateProductId();
        //添加订单详情
        orderMapper.insertNewOrder(orderID, formOrder.getOrderPrice(), OrderEnum.PREPARE_TO_PAY.getOrderStatus(), 0,
                new java.sql.Date(date.getTime()), formOrder.getAddressID(), formOrder.getUserID());
        //添加订单产品表
        for (FormProduct formProduct : productList) {
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOrderId(orderID);
            orderProduct.setProductId(formProduct.getProductId());
            orderProduct.setProductQuantity(formProduct.getProductQuantity());
            orderProductMapper.insert(orderProduct);
        }
        return orderID;
    }

    /**
     * 按照用户id查找订单方法
     * @param userID
     * @return
     */
    @Override
    public List<OrderMasterVO> selectOrderListByUserID(Integer userID) {
        List<Order> orderList = orderMapper.selectAllOrderByUserID(userID);
        List<OrderMasterVO> orderMasterVOList = new ArrayList<OrderMasterVO>();
        if(orderList == null || orderList.isEmpty()){
            return null;
        }
        //封装数据
        for(Order order : orderList){
            OrderMasterVO orderMasterVO = new OrderMasterVO();
            orderMasterVO.setOrderId(order.getOrderId());
            orderMasterVO.setOrderPrice(order.getOrderPrice());
            orderMasterVO.setOrderStatus(order.getOrderStatus());
            orderMasterVO.setOrderDate(order.getOrderDate());
            orderMasterVOList.add(orderMasterVO);
        }
        return orderMasterVOList;
    }

    @Override
    public List<OrderMasterVO> selectOrderListByUserIDAndStatus(Integer userID, OrderEnum orderEnum) {
        List<Order> orderList = orderMapper.selectAllOrderByUserIDandStatus(userID, orderEnum);
        List<OrderMasterVO> orderMasterVOList = new ArrayList<>();
        if(orderList.isEmpty())
            return null;
        //封装数据
        for(Order order : orderList){
            OrderMasterVO orderMasterVO = new OrderMasterVO();
            orderMasterVO.setOrderId(order.getOrderId());
            orderMasterVO.setOrderPrice(order.getOrderPrice());
            orderMasterVO.setOrderStatus(order.getOrderStatus());
            orderMasterVO.setOrderDate(order.getOrderDate());
            orderMasterVOList.add(orderMasterVO);
        }
        return orderMasterVOList;
    }

//    @Override
//    public List<OrderMasterVO> selectOrderList() {
//        return null;
//    }
}
